<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">
            <el-form-item>
              <el-button type="primary" icon="Plus" @click="handleAdd">添加分类</el-button>
            </el-form-item>
            <el-form-item label="关键词：" prop="keyword">
              <el-input v-model="queryParams.keyword" placeholder="请输入用户名称..." maxlength="100" clearable />
            </el-form-item>
            <el-form-item label="启用状态" prop="status">
              <el-select v-model="queryParams.status" class="m-2" placeholder="请选择" clearable  @change="handleSearch">
                <el-option
                  v-for="item in [
                    { value: 1, label: '启用中' },
                    { value: 0, label: '禁止中' }
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click.prevent="handleSearch">搜索</el-button>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-loading="tableLoading"
          :default-expand-all="false"
          row-key="id"
          :data="tableData"
          stripe
          border
          :height="settings.tableHeight()"
        >
          <el-table-column fixed label="序号" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed label="ID" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.id}} / {{ scope.row.parentId}}</span>
            </template>
          </el-table-column>
          <el-table-column fixed label="分类名称"  align="center">
            <template v-slot="scope">
              <span>{{ scope.row.title}}（{{scope.row.children?.length || 0}}）</span>
            </template>
          </el-table-column>
          <el-table-column fixed label="排序" align="center">
            <template #default="{ row, $index }">
              <el-input-number
                controls-position="right"
                style="width: 120px; text-align: center"
                @change="handleStatus(row, 'sorted')"
                v-model="row.sorted"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="帖文数" prop="postCount" align="center" />
          <el-table-column label="是否启用" width="200" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                @change="handleStatus(scope.row, 'status')"
                :active-value="1"
                active-text="启用中"
                inactive-text="已禁止"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTimeToStr(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTimeToStr(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="right" width="320">
            <template #default="scope">
              <el-button icon="edit" type="info" size="small" @click.stop="handleCopy(scope.row)">复制</el-button>
              <el-button icon="plus" type="success" v-if="scope.row.parentId ==0" size="small" @click.stop="handleAddChildren(scope.row)">添加子分类</el-button>
              <el-button icon="edit" type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
              <el-button icon="remove" type="danger" size="small" @click.stop="handleDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="kva-pagination-box center">
          <el-pagination
            :current-page="queryParams.pageNo"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </home-page-header>
    </div>
    <add-category ref="addRef" @load="handleSearch"></add-category>
  </div>
</template>
<script setup>
  import settings from '@/settings'
  import KVA from '@/utils/kva.js'
  import { formatTimeToStr } from '@/utils/date.js'
  import AddCategory from './components/AddCategory.vue'
  import { copyData, findPagesAll, delById, updateStatus } from '@/api/course/category.js'

  // 搜索属性定义
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 30,
    status: '',
    keyword: ''
  })

  // 定义响应式得列表数据容器
  const tableData = ref([])
  const tableLoading = ref(false)
  const searchForm = ref({})

  // 编辑添加相关
  const addRef = ref({})

  // 加载数据
  const handleLodeData = async () => {
    tableLoading.value = true
    const resp = await findPagesAll(queryParams)
    tableLoading.value = false
    tableData.value = resp.data
  }

  // 搜索
  const handleSearch = () => {
    queryParams.pageNo = 1
    handleLodeData()
  }

  // 重置
  const handleReset = () => {
    searchForm.value.resetFields()
    handleSearch()
  }

  // 分页size更改
  const handleSizeChange = (size) => {
    queryParams.pageSize = size
    handleLodeData()
  }

  // 分页pageNo更改
  const handleCurrentChange = (pno) => {
    queryParams.pageNo = pno
    handleLodeData()
  }

  // 添加事件
  const handleAdd = () => {
    addRef.value.handleOpen(null,tableData.value.length+1)
  }

  // 编辑
  const handleEdit = (row) => {
    addRef.value.handleOpen(row.id)
  }

  // 添加子分类
  const handleAddChildren = (row) => {
    addRef.value.handleOpenChildren(row.id)
  }

  // 删除
  const handleDel = (row) => {
    var postCount = row.postCount
    if (postCount > 0) {
      KVA.warning('无法删除，该分类下存在帖文！')
      return
    }

    KVA.confirm('警告', '<strong>您确定要执行此次操作吗？</strong>', { icon: 'success' }).then(async () => {
      if (row.children && row.children.length > 0) {
        KVA.error('存在绑定关系,无法删除?')
        return
      }
      await delById(row.id)
      KVA.notifySuccess('删除成功!')
      handleLodeData()
    })
  }

  // 更新状态
  const handleStatus = async (row, field) => {
    await updateStatus(row.id, field, row[field])
    handleLodeData()
    KVA.notifySuccess('操作成功!')
  }

  const handleCopy = async (row)=>{
    await copyData(row.id);
    KVA.success("复制成功!!")
    handleLodeData()
  }

  onMounted(() => {
    handleLodeData()
  })
</script>
